limsResult.runOrderTaskDetailPage = {
    // 哪些分析项是富文本外链编辑
    richLinkAnalyte: null,

    getBtnToolbar: function (runId) {
        var _this = this;
        var items = [{
            type: 'button',
            text: 'GIKAM.BUTTON.BACK',
            icon: 'back',
            onClick: function () {
                if (_this.param.modal) {
                    Gikam.getLastModal().close()
                } else {
                    workspace.window.goBack()
                }
            }
        }, {
            type: 'button',
            text: 'GIKAM.WORKFLOW.BUTTON.SUBMIT',
            // class: 'blue',
            icon: 'submit', color: 'success',
            // color: 'white',
            onClick: function () {
                _this.submitRunSingle(runId)
            }
        }]
        return {
            type: 'btnToolbar',
            items: items
        }
    },

    // 提交结果录入
    submitRunSingle: function (runId) {
        let grid = Gikam.getComp('run-list-grid')
        var _this = this
        if (!runId) {
            return
        }
        Gikam.confirm('GIKAM.MODAL.SUBMIT', 'GIKAM.TIP.SUBMIT', function () {
            workspace.window.showMask();
            Gikam.postText(limsResult.runUrl + '/action/submit',
                Gikam.getJsonWrapper(null, [null, [{id: runId}]])).done(function (result) {
                grid.refresh();
                workspace.window.goBack()
            }).always(function () {
                workspace.window.closeMask();
            });
        })
    },

    refreshGridColumns: function (grid, runId) {
        var _this = this;
        var url = Gikam.printf(limsResult.baseUrl + '/r/{runId}/result-to-columns/queries', {
            runId: runId
        });
        limsResult.analyteColumns = limsResult.getRunOrderTaskGridColumns();
        Gikam.postSync(url).done(function (data) {
            if (Gikam.isNotEmpty(data)) {
                // 富文本外链分析项记录到richLinkAnalyte键值对中
                _this.richLinkAnalyte = new Map();
                Gikam.each(data.rows, function (index, item) {
                    var analyteId = item.analyteId;
                    // var editor = item.calcFlag == '0';
                    var editor = item.editFlag === '1';
                    var fieldType = item.analType === 'N' ? 'number' : 'text';
                    var selectData = [];
                    if (item.ext$.possibleresultinfo) {
                        fieldType = 'select';
                        Gikam.each(JSON.parse(item.ext$.possibleresultinfo), function (index, item2) {
                            selectData.push({
                                text: item2.originalResult,
                                value: item2.originalResult
                            });
                        });
                    }
                    if (item.analType === "F") {
                        // 2023-02-27 迁移寻因
                        if (item.writeFlag === '1') {
                            limsResult.analyteColumns.push({
                                field: 'ext$.' + analyteId,
                                title: item.analyte,
                                type: 'link',
                                validators: ['notEmpty'],
                                items: selectData,
                                width: 180,
                                sort: false,
                                editor: editor,
                                autoSave: false,
                                styleFormatter: function (row) {
                                    // return {color: '#FF2D2D'}
                                    return {
                                        backgroundColor: row.ext$.resultinfo ? eval('(' + row.ext$.resultinfo + ')')[analyteId] : null
                                    }
                                }
                            });
                        } else {
                            limsResult.analyteColumns.push({
                                field: 'ext$.' + analyteId,
                                title: item.analyte,
                                type: 'link',
                                items: selectData,
                                width: 180,
                                sort: false,
                                editor: editor,
                                autoSave: false,
                            });
                        }
                        // 键为field:ext$.analyteId，值为t_lims_result表的Id
                        // 分析项结果行转列，仅获取了第一行的数据，每个样本的分析项结果表的Id都不相同
                        _this.richLinkAnalyte.set('ext$.' + analyteId, item.id);
                    } else if (item.writeFlag === '1') {
                        limsResult.analyteColumns.push({
                            field: 'ext$.' + analyteId,
                            title: item.analyte,
                            type: fieldType,
                            validators: ['notEmpty'],
                            items: selectData,
                            width: 180,
                            sort: false,
                            editor: editor,
                            autoSave: false,
                            onChange: function (field, value, index) {
                                _this.saveResult(analyteId, value, this.getData()[index].id, function () {
                                    Gikam.getComp('result-run-order-task-with-analyte-grid').refreshRowByIndex(index);
                                });
                            },
                            onBeforeEditorRender: function (row) {
                                return row.ext$.resultinfo && eval('(' + row.ext$.resultinfo + ')').hasOwnProperty(analyteId);
                            },
                            styleFormatter: function (row) {
                                return {
                                    backgroundColor: row.ext$.resultinfo ? eval('(' + row.ext$.resultinfo + ')')[analyteId] : null
                                }
                            }
                        });
                    } else {
                        limsResult.analyteColumns.push({
                            field: 'ext$.' + analyteId,
                            title: item.analyte,
                            type: fieldType,
                            items: selectData,
                            width: 180,
                            sort: false,
                            editor: editor,
                            autoSave: false,
                            onChange: function (field, value, index) {
                                _this.saveResult(analyteId, value, this.getData()[index].id, function () {
                                    Gikam.getComp('result-run-order-task-with-analyte-grid').refreshRowByIndex(index);
                                });
                            },
                            onBeforeEditorRender: function (row) {
                                return row.ext$.resultinfo && eval('(' + row.ext$.resultinfo + ')').hasOwnProperty(analyteId);
                            },
                            styleFormatter: function (row) {
                                return {
                                    backgroundColor: row.ext$.resultinfo ? eval('(' + row.ext$.resultinfo + ')')[analyteId] : null
                                }
                            }
                        });
                    }
                });
            }
        });
        grid.cleanData();
        grid.options.columns = limsResult.analyteColumns;
        grid.refreshColumns(limsResult.analyteColumns);
    },

    ckeditorResult: function (analyteId, orderTaskId) {

    },

    saveResult: function (analyteId, value, orderTaskId, callback) {
        var url = Gikam.printf(limsResult.baseUrl + '/order-task/{orderTaskId}/update', {
            orderTaskId: orderTaskId
        });
        workspace.window.showMask();
        Gikam.postText(url, Gikam.getJsonWrapper(null, [null, [{
            originalResult: value,
            analyteId: analyteId,

        }]])).done(function (data) {
            callback && callback();
        }).always(function () {
            workspace.window.closeMask();
        });
    },

    getRunOrderTaskTab: function (runId) {
        var _this = this;

        return {
            type: 'tab',
            panels: [{
                title: 'T_LIMS_ORDER_TASK.TITLE.SAMPLE',
                items: [{
                    type: 'grid',
                    height: 230,
                    id: 'result-run-order-task-with-analyte-grid',
                    page: false,//工序样本
                    columns: limsResult.getRunOrderTaskGridColumns(),
                    generalButtonGroup: ['refresh', 'config'],
                    url: limsResult.orderTaskUrl + '/result/queries',
                    requestData: {
                        status_SB: 'logged',
                        flag_EQ: '1',
                        runId_EQ: runId,
                        queries_raw: '1'
                    },
                    onRendered: function () {
                        var grid = Gikam.getComp('result-run-order-task-with-analyte-grid')
                        _this.refreshGridColumns(grid, runId)
                    },
                    onCellClick: function (field, row, index) {
                        // 分析项ext$.analyteId，字段为t_lims_analyte的id,详情必须为t_lims_result的id，判断富文本外链分析项
                        // 将orderTaskId的值以及分析项的field(ext$.analyteId)传给后台，查询出唯一的工序任务分析项数据
                        _this.richLinkAnalyte.has(field) && limsResult.loadAndEditRichText(row.id, field, 'result-run-order-task-with-analyte-grid');
                    },
                    toolbar: [{
                        type: 'button',
                        text: 'GIKAM.BUTTON.EXPORT',
                        icon: 'export',
                        onClick: function () {
                            if (Gikam.isEmpty(_this.param.id)) {
                                Gikam.alert('MODULE.BUSINESS.RESULT.TIP.CHOOSE_ONE_RUN');
                                return;
                            }
                            Gikam.getText(IFM_CONTEXT + '/core/module/item/files/template-urls' + Gikam.param({
                                templateCode: 'LimsResultExportTemplate',
                                service: 'LimsResultExportTemplate',
                                id : _this.param.id
                            })).done(function (url) {
                                Gikam.download(url)
                            })
                        }
                    }, {
                        type: 'button',
                        text: 'GIKAM.BUTTON.IMPORT',
                        icon: 'upload',
                        onClick: function () {
                            if (Gikam.isEmpty(_this.param.id)) {
                                Gikam.alert('MODULE.BUSINESS.RESULT.TIP.CHOOSE_ONE_RUN');
                                return;
                            }
                            Gikam.create('simpleUploader', {
                                id: 'result-info-import',
                                dbTable: 'T_LIMS_RUN',
                                bizId: _this.param.id,
                                autoClose: true,
                                multiple: false,
                                onAfterClose: function (fields) {
                                    if (Gikam.isNotEmpty(fields)) {
                                        // 获取固定列的数量：
                                        let fixedColumn = limsResult.getRunOrderTaskGridColumns();
                                        let size = fixedColumn.length + 2;
                                        workspace.window.showMask();
                                        var url = Gikam.printf(IFM_CONTEXT + '/core/module/item/files/{id}/action/import/' + 'limsResultImportFileFunction', {
                                            id: fields[0].id
                                        }) + Gikam.param({
                                            fixedColumnSize: size,
                                            id: _this.param.id
                                        });
                                        Gikam.post(url).done(req => {
                                            Gikam.getComp('result-run-order-task-with-analyte-grid').refresh();
                                            if (req.message){
                                                Gikam.alert(req.message)
                                            }
                                            if (req.url){
                                                Gikam.download(req.url);
                                            }
                                        }).always(function () {
                                            workspace.window.closeMask();
                                        });
                                    }
                                }
                            });
                        }
                    }, {
                        type: 'button',
                        text: 'GIKAM.TAB.STOP_TASK',
                        icon: 'select',
                        onClick: function () {
                            let grid = Gikam.getComp('result-run-order-task-with-analyte-grid');
                            let selections = grid.getSelections();
                            if (Gikam.isEmpty(selections)) {
                                Gikam.alert('GIKAM.TIP.CHOOSE_ONE_ITEM');
                                return;
                            }
                            // 先校验通过再弹窗
                            let checkUrl = limsResult.runUrl + '/check';
                            Gikam.postSync(checkUrl, Gikam.getJsonWrapper(null, [null, selections]))
                                .done(function (message) {
                                if (message === 200) {
                                    Gikam.createLimsModal({
                                        title: 'GIKAM.TAB.STOP_TASK',
                                        height: 220,
                                        width: 380,
                                        onConfirm: function () {
                                            var form = Gikam.getComp('confirm-form');
                                            if (form.validate()) {
                                                let data = form.getData();
                                                workspace.window.showMask();
                                                Gikam.postText(limsResult.runUrl + '/action/abnormal',
                                                    Gikam.getJsonWrapper(data, [null, selections])).done(function (result) {
                                                    grid.refresh();
                                                }).always(function () {
                                                    Gikam.getLastModal().close();
                                                    workspace.window.closeMask();
                                                });
                                            }
                                        },
                                        m: {
                                            type: 'form',
                                            id: 'confirm-form',
                                            fields: [{
                                                field: 'reason',
                                                title: 'T_LIMS_ORDER_TASK.REASON',
                                                validators: ['notEmpty'],
                                                type: 'textarea',
                                                height: 100,
                                            }],
                                            columns: 1,
                                        }
                                    })
                                }
                            })
                        }
                    }, {
                        type: 'button',
                        text: 'MODULE.BUSINESS.BACKTRACK',
                        icon: 'view-audit',
                        onClick: function () {
                            // 追溯
                            var grid = Gikam.getComp('result-run-order-task-with-analyte-grid');
                            var selections = grid.getSelections();
                            if (Gikam.isEmpty(selections)) {
                                Gikam.alert('GIKAM.TIP.CHOOSE_ONE_ITEM');
                                return;
                            }
                            Gikam.create('modal', {
                                title: 'MODULE.BUSINESS.RESULT.TITLE.BACKTRACK',
                                url: limsResult.baseUrl + '/page/result-back-track' + Gikam.param({
                                    sampleCodes: selections.map(s => s.sampleCode).join(","),
                                    sampleIds: selections.map(r => r.sampleId).join(",")
                                }),
                                height: 650
                            });
                        }
                    }]
                }]
            }, {
                title: 'MODULE.BUSINESS.RESULT.TAB.DERIVATIVE',
                items: [{
                    type: 'grid',
                    id: 'result-all-derivative-grid',
                    columns: limsResult.getAllDerivativeEditListColumns(),
                    deleteFormatter: function (row) {
                        return row.sampleCode;
                    },
                    url: Gikam.printf(limsResult.derivativelUrl + '/runs/{runId}/queries', {
                        runId: runId
                    }),
                    toolbar: [{//添加衍生物
                        type: 'button',
                        text: 'MODULE.BUSINESS.RESULT.BUTTON.ADD_DERIVATIVE',
                        icon: 'add',
                        onClick: function () {
                            _this.addDerivative();
                        }
                    }, {
                        type: 'button',
                        text: 'GIKAM.BUTTON.DELETE',
                        icon: 'remove',
                        onClick: function () {
                            Gikam.getComp('result-all-derivative-grid').deleteRows(limsResult.derivativelUrl);
                        }
                    }]
                }]
            }, {
                title : 'T_LIMS_ORDER_TASK.TITLE.BOARD', // 布板信息
                items : [{
                    type : 'iframe',
                    src : '/static/basemodule/business/run-board-readonly/index.html',
                    id : 'ksh-run-board-readonly-iframe'
                }]
            },{
                title: 'GIKAM.FILE.ATTACHMENT',
                items: [{
                    type: 'uploader',
                    id: 'result-uploader',
                    filter: false,
                    dbTable: 'T_LIMS_RUN',
                    bizId: _this.param.runCode,
                    onBeforeUpload: function () {
                        if (!_this.param.runCode){
                            Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM', 200)
                            return false
                        }
                    },
                    onBeforeDelete: function () {
                        let grid = this.grid;
                        let selections = grid.getSelections();
                        if (Gikam.isEmpty(selections)) {
                            Gikam.alert('GIKAM.TIP.CHOOSE_AT_LEAST_ONE_ITEM');
                            return false;
                        }
                        let bool = selections.filter(item => item.bizCategory === 'dispatch');
                        if (bool.length > 0) {
                            Gikam.alert('NO.DELETE.FJTYPE.OF.DISPATCH');
                            return false;
                        }
                    },
                    formatterGridColumns: function (columns) {
                        columns.splice(2, 0, {
                            field: 'bizCategory',
                            title: 'LIMS.MODLE.FILE.FILETYPE',
                            type: 'select',
                            width: 140,
                            category: 'sys',
                            param: {
                                codeCategoryId: 'fjType'
                            }
                        });
                        return Gikam.getFormatterGridColumns(columns, true);
                    },
                    onBeforeFilesUpload: function (files) {
                        files.map(file => file.bizCategory = 'result');
                        return true;
                    }
                }]
            }, {
                title: 'MODULE.COREDATA.TEST.TAB.MATERIAL_ITEM',
                items: [{
                    type: 'grid',
                    id: 'result-all-material-grid',
                    service: 'limsRunMaterialServiceImpl',
                    columns: limsResult.getMaterialListColumns(),
                    url: limsResult.runMaterialUrl + '/queries',
                    requestData: {
                        runId_EQ: runId
                    }
                }]
            }, {
                title: 'MODULE.COREDATA.TEST.TAB.EQUIP_ITEM',
                items: [{
                    type: 'grid',
                    id: 'result-all-equipt-grid',
                    columns: limsResult.getEquiptListColumns(true),
                    url: limsResult.runEquipUrl + '/queries',
                    requestData: {
                        runId_EQ: runId
                    }
                }]
            }],
            onActived: function (runId) {
                if (_this.param.id){
                    Gikam.postSync(limsResult.boardHoleUrl + '/queries', Gikam.getJsonWrapper({
                        f: {
                            boardId_EQ: _this.param.id
                        },
                        o: [{
                            y : 'asc'
                        },{
                            x : 'asc'
                        }],
                        n: -1, s: -1
                    })).done(function (data) {
                        const  dom=document.querySelector("#ksh-run-board-readonly-iframe >iframe");
                        let flag=false;  //是否初次加载
                        dom.onload=function(){
                            flag =true;
                            dom.contentWindow.postMessage({
                                type:1,
                                data: data.rows
                            }, "*");
                        };
                        if(!flag){
                            dom.contentWindow.postMessage({
                                type:1,
                                data: data.rows
                            }, "*");
                        }
                    });
                }else{
                    const  dom=document.querySelector("#ksh-run-board-readonly-iframe >iframe");
                    if (Gikam.isEmpty(dom)) return;
                    let flag=false;  //是否初次加载
                    dom.onload=function(){
                        flag =true;
                        dom.contentWindow.postMessage({
                            type:1,
                            data: []
                        }, "*");
                    };
                    if(!flag){
                        dom.contentWindow.postMessage({
                            type:1,
                            data: []
                        }, "*");
                    }
                }
            }
        }
    },

    // 布板信息
    boardTab : function(){
        let _this = this;
        return{
            type : 'layout',
            center : {
                items : [{
                    type : 'iframe',
                    src : '/static/basemodule/business/run-board/index.html',
                    id : 'ksh-run-board-iframe'
                }]
            }
        }
    },

    // 加载布板信息
    loadRunBoardDetail : function(){

        Gikam.postSync(limsResult.boardHoleUrl + '/queries', Gikam.getJsonWrapper({
            f: {
                boardId_EQ: row.id
            },
            o: [{
                y : 'asc'
            },{
                x : 'asc'
            }],
            n: -1, s: -1
        })).done(function (data) {
            const  dom=document.querySelector("#ksh-run-board-iframe >iframe");
            let flag=false;  //是否初次加载
            dom.onload=function(){
                flag =true;
                dom.contentWindow.postMessage({
                    type:1,
                    data: data.rows
                }, "*");
            };
            if(!flag){
                dom.contentWindow.postMessage({
                    type:1,
                    data: data.rows
                }, "*");
            }
        });
    },

    // 添加衍生物
    addDerivative: function () {
        var activedRow = Gikam.getComp('run-list-grid').getActivedRow();
        if (Gikam.isEmpty(activedRow)) {
            return;
        }
        Gikam.create('modal', {
            title: 'MODULE.BUSINESS.RESULT.BUTTON.ADD_DERIVATIVE',
            url: limsResult.baseUrl + '/page/derivative/detail' + Gikam.param({
                runId: activedRow.id
            }),
            onAfterClose: function (data) {
                Gikam.getComp('result-all-derivative-grid').refresh();
            }
        })
    },

    createPage: function () {
        var _this = this;
        var render = workspace.window.$dom;
        if (_this.param.modal) {
            render = Gikam.getLastModal().window.$dom;
        }
        Gikam.create('layout', {
            center: {
                items: [this.getBtnToolbar(_this.param.id), _this.getRunOrderTaskTab(_this.param.id)]
            },
            renderTo: render
        });
        return this;

    },

    init: function (param) {
        this.param = param
        this.createPage()
    }
}
